/**
 * Copyright (C) 2015-2016 Guangzhou Xunhong Network Technology Co., Ltd. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jxccp.ui.view;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.jxccp.im.JXErrorCode;
import com.jxccp.im.JXErrorCode.Mcs;
import com.jxccp.im.callback.JXEventListner;
import com.jxccp.im.chat.manager.JXEventNotifier;
import com.jxccp.im.chat.manager.JXImManager;
import com.jxccp.im.chat.mcs.entity.JXCustomerServiceEntity;
import com.jxccp.im.chat.mcs.entity.JXServiceType;
import com.jxccp.im.chat.mcs.entity.JXWorkgroup;
import com.jxccp.im.util.StringUtil;
import com.jxccp.im.util.log.JXLog;
import com.jxccp.ui.JXAccountHelper;
import com.jxccp.ui.JXAccountHelper.OnInitMcsRequestCallback;
import com.jxccp.ui.JXConstants;
import com.jxccp.ui.JXUiHelper;
import com.jxccp.ui.R;
import com.jxccp.ui.model.JXRequestCusServiceTask;
import com.jxccp.ui.service.JXMessageBoxService;
import com.jxccp.ui.service.JXNotifyManager;
import com.jxccp.ui.utils.JXCommonUtils;
import com.jxccp.ui.view.adapter.JXServiceTypeAdapter;
import com.jxccp.ui.view.adapter.JXWorkGroupAdapter;

import java.util.List;

/**
 * 客服用户初始化界面
 */
public class JXInitActivity extends JXBaseFragmentActivity implements JXWorkGroupAdapter.OnEnterGroupListener,
        JXMessageBoxService.MessageBoxListener, JXEventListner, View.OnClickListener {
    public static final String TAG = JXInitActivity.class.getSimpleName();

    private ListView groupListView;

    private ProgressBar loadingProgressBar;

    protected ImageView actionbarLeftView;

    protected ImageView actionbarRightView;

    protected ImageView   actionbarReturn;

    protected TextView actionbarRightTextView;

    protected TextView actionbarTitleView;

    protected TextView badgeTextView;

    protected ImageView badgeView;

    protected RelativeLayout badgeLayout;

    protected RelativeLayout titleLayout;

    private String extendData;

    private String chatkey = null;
    private String chatTitlekey = null;
    private boolean msgBoxEnable;
    private int chatType = 0;
    private String suborgId;
    private String channelNo;
    private boolean backToServiceType = false;
    private JXCustomerServiceEntity currentCustomerServiceEntity;
    JXWorkGroupAdapter workGroupAdapter;
    JXServiceTypeAdapter serviceTypeAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        // 获取扩展信息
        extendData = getIntent().getStringExtra(JXConstants.EXTRA_CHAT_EXTEND_DATE);
        chatkey = getIntent().getStringExtra(JXConstants.EXTRA_CHAT_KEY);
        chatTitlekey = getIntent().getStringExtra(JXConstants.EXTRA_CHAT_TITLE_KEY);
        msgBoxEnable = getIntent().getBooleanExtra(JXConstants.EXTRA_MSG_BOX_KEY, false);
        Log.d(TAG, "extendData: " + extendData);

        chatType = getIntent().getIntExtra(JXConstants.EXTRA_CHAT_TYPE,JXChatView.CHATTYPE_CUSTOMER_SERVICE);
        this.suborgId = this.getIntent().getStringExtra(JXConstants.EXTRA_SUBORG_ID_KEY);
        JXLog.d("[JXInitActivity.onCreate]extendData : " + extendData+" , suborgId = "+suborgId);
        if (TextUtils.isEmpty(suborgId)){
            String appkey = JXImManager.getInstance().getAppKey();
            int index = appkey.indexOf("#");
            if (index > -1) {
                suborgId = appkey.substring(0, index);
            } else {
                suborgId = appkey;
            }
        }
        JXUiHelper.getInstance().setSuborgId(suborgId);
        JXImManager.McsUser.getInstance().setSuborgId(suborgId);

        channelNo = getIntent().getStringExtra(JXConstants.EXTRA_CHANNEL_NO);
        if (!StringUtil.isNullOrEmpty(channelNo)){
            JXUiHelper.getInstance().setCurrentChannelNo(channelNo);
            JXImManager.getInstance().setChannelNumber(channelNo);
        }

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
//            Intent service = new Intent();
//            service.setClass(getApplicationContext(), JXCustomerService.class);
//            startForegroundService(service);
//        }else {
//            Intent service = new Intent();
//            service.setClass(getApplicationContext(), JXCustomerService.class);
//            startService(service);
//        }
        JXNotifyManager.getInstance().setApplicationContext(getApplicationContext());


        setContentView(R.layout.jx_activity_login);
        actionbarRightView = (ImageView)findViewById(R.id.iv_right);
        actionbarRightTextView = (TextView)findViewById(R.id.tv_right);
        actionbarLeftView = (ImageView)findViewById(R.id.iv_left);
        actionbarTitleView = (TextView)findViewById(R.id.tv_actionTitle);
        actionbarReturn = (ImageView) findViewById(R.id.iv_return);
        badgeView = (ImageView) findViewById(R.id.iv_badge);
        badgeTextView = (TextView)findViewById(R.id.tv_badge);
        badgeLayout = (RelativeLayout)findViewById(R.id.rl_badge);
        titleLayout = (RelativeLayout) findViewById(R.id.rl_title_layout);
        if (chatType != JXChatView.CHATTYPE_MESSAGE_BOX) {
            actionbarTitleView.setText(R.string.jx_choose_group);
        }
        actionbarRightView.setImageResource(R.drawable.jx_ic_leave_message);
        if(msgBoxEnable){
            badgeLayout.setVisibility(View.VISIBLE);
        }
        LayoutParams layoutParams = (LayoutParams)badgeLayout.getLayoutParams();
        if(layoutParams != null){
            layoutParams.setMargins(0, 0, JXCommonUtils.dip2px(this, 60), 0);
            badgeLayout.setLayoutParams(layoutParams);
            badgeView.setImageResource(R.drawable.jx_message_box);
            badgeView.setVisibility(View.VISIBLE);
        }

        groupListView = (ListView)findViewById(R.id.lv_groups);
        loadingProgressBar = (ProgressBar)findViewById(R.id.pb_loading);

        if (JXUiHelper.getInstance().getmTitleBgColorId() != JXUiHelper.INVALID_INT) {
            titleLayout.setBackgroundColor(getResources().getColor(JXUiHelper.getInstance().getmTitleBgColorId()));
        }

        if (JXUiHelper.getInstance().getmTitleTextColorResId() != JXUiHelper.INVALID_INT) {
            actionbarTitleView.setTextColor(
                    getResources().getColor(JXUiHelper.getInstance().getmTitleTextColorResId()));
        }

        if (JXUiHelper.getInstance().getmTitleLeftImgResId() != JXUiHelper.INVALID_INT) {
            actionbarLeftView.setImageResource(JXUiHelper.getInstance().getmTitleLeftImgResId());
        }

        JXImManager.Message.getInstance().registerEventListener(this);
        // 客服请求的初始化
        JXAccountHelper.getInstance().initMcsRequest(getApplicationContext(), new OnInitMcsRequestCallback() {

            @Override
            public void onInitMcsResult(final int code) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        if (code == Mcs.MCS_USER_INIT_SUCCESS) {
                            if (chatType == JXChatView.CHATTYPE_MESSAGE_BOX) {
                                requestMessagebox(chatTitlekey);
                            }else {
                                JXWorkgroup workgroup = JXImManager.McsUser.getInstance().isNeedRequest(JXUiHelper.getInstance().getSuborgId());
                                if(workgroup == null){
                                    if(chatkey == null){
                                        fetchWorkgroupFromServer();
                                    }else{
                                        requestCustomerService(chatkey, chatTitlekey);
                                    }
                                }else{
                                    if (chatkey!=null && !chatkey.equals(workgroup.getMcsId())) {
                                        reRequestCustomerServiceByChatKey(workgroup.getMcsId(),chatkey,chatTitlekey);
                                    }else if (JXUiHelper.getInstance().reRequestAfterChangeChannelEnable()){
                                        if (channelNo == null || JXUiHelper.getInstance().isSameChannelNo(channelNo)){
                                            requestCustomerService(workgroup.getMcsId(), workgroup.getDisplayName());
                                        }else{
                                            reRequestCustomerService(workgroup.getMcsId());
                                        }
                                    }else {
                                        requestCustomerService(workgroup.getMcsId(), workgroup.getDisplayName());
                                    }
                                }
                            }
                        } else if (code == JXErrorCode.APPKEY_NOT_EXIST) {
                            JXCommonUtils.showToast(getApplicationContext(),
                                    getString(R.string.jx_appkey_not_exist));
                            finish();
                        } else {
                            JXCommonUtils.showToast(getApplicationContext(),
                                    getString(R.string.jx_request_customerFailed));
                            finish();
                        }
                    }
                });
            }
        });
    }

    private JXMessageBoxService currentMessageBoxService;
    @Override
    protected void onResume() {
        super.onResume();
        if(msgBoxEnable){
            setUpBadgeUnread(JXUiHelper.getInstance().getMessageBoxUnreadCount());
            synchronized (JXMessageBoxService.class) {
                if(currentMessageBoxService == null){
                    currentMessageBoxService = new JXMessageBoxService();
                    currentMessageBoxService.setMessageBoxListener(this);
                }else{
                    currentMessageBoxService.setMessageBoxListener(null);
                    currentMessageBoxService.cancel(true);
                    currentMessageBoxService = new JXMessageBoxService();
                }
                currentMessageBoxService.execute();
            }
        }
    }
    /**
     * @date 2015年9月24日
     * @Description: 请求客服
     * @throws
     */
    private void requestCustomerService(final String skillId, final String displayName) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Intent intent = new Intent();
                    intent.setClass(JXInitActivity.this, JXChatUIActivity.class);
                    intent.putExtra(JXConstants.EXTRA_CHAT_KEY, skillId);
                    intent.putExtra(JXConstants.EXTRA_CHAT_TITLE_KEY, displayName);
                    intent.putExtra(JXConstants.EXTRA_CHAT_EXTEND_DATE, extendData);
                    intent.putExtra(JXConstants.EXTRA_CHAT_TYPE, JXChatView.CHATTYPE_CUSTOMER_SERVICE);
                    startActivity(intent);
                    finish();
                }
            });
    }

    private void requestMessagebox( final String displayName) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Intent intent = new Intent();
                intent.setClass(JXInitActivity.this, JXChatUIActivity.class);
                intent.putExtra(JXConstants.EXTRA_CHAT_TYPE, JXChatView.CHATTYPE_MESSAGE_BOX);
                intent.putExtra(JXConstants.EXTRA_CHAT_TITLE_KEY, displayName);
                startActivity(intent);
                finish();
            }
        });
    }


    private void fetchWorkgroupFromServer() {
        new AsyncTask<Void, Void, JXCustomerServiceEntity>() {
            boolean hasException = false;

            protected void onPreExecute() {
                loadingProgressBar.setVisibility(View.VISIBLE);
            };

            @Override
            protected JXCustomerServiceEntity doInBackground(Void... params) {
                try {
                    JXCustomerServiceEntity jxCustomerServiceEntity = JXImManager.McsUser.getInstance()
                            .getCustomerServicesWithServiceType(JXUiHelper.getInstance().getSuborgId());
                    return jxCustomerServiceEntity;
                } catch (Exception e) {
                    e.printStackTrace();
                    hasException = true;
                }
                return null;
            }

            protected void onPostExecute(JXCustomerServiceEntity result) {
                loadingProgressBar.setVisibility(View.GONE);
                if (result != null) {
                    currentCustomerServiceEntity = result;
                    if (result.getServerTypes()== null || result.getServerTypes().isEmpty()){
                        //没有服务类型
                        if(result.getWorkgroupList().size() == 1){
                            //如果只一个有技能组直接进入
                            requestCustomerService(result.getWorkgroupList().get(0).getMcsId(), result.getWorkgroupList().get(0).getDisplayName());
                        }else{
                            if (workGroupAdapter == null){
                                workGroupAdapter = new JXWorkGroupAdapter(JXInitActivity.this, result.getWorkgroupList());
                                workGroupAdapter.setOnEnterGroupListener(JXInitActivity.this);
                            }
                            groupListView.setAdapter(workGroupAdapter);
                        }
                    }else {
                        //有服务类型 先显示服务类型
                        if (serviceTypeAdapter == null){
                            serviceTypeAdapter = new JXServiceTypeAdapter(JXInitActivity.this, result.getServerTypes());
                            serviceTypeAdapter.setOnChooseServiceTypeListener(onChooseServiceTypeListener);
                        }
                        groupListView.setAdapter(serviceTypeAdapter);
                    }
                } else {
                    if (hasException) {
                        JXCommonUtils.showToast(getApplicationContext(),
                                getString(R.string.jx_loadin_groups_failed));
                        finish();
                    }
                }
            };
        }.execute();
    }

    @Override
    public void onEnter(String mcsId, String displayName) {
        requestCustomerService(mcsId, displayName);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.iv_right) {
            startActivity(new Intent(JXInitActivity.this, JXLeaveMsgActivity.class).putExtra
                    (JXConstants.EXTRA_SKILLS_ID, "").putExtra
                    (JXConstants.EXTRA_LEAVE_MSG_TYPE, JXLeaveMsgActivity.LEAVE_MSG_ONLINE));
        }
    }

    @Override
    protected void onDestroy() {
        if(currentMessageBoxService != null){
            currentMessageBoxService.setMessageBoxListener(null);
        }
        JXImManager.Message.getInstance().removeEventListener(this);
        super.onDestroy();
        JXAccountHelper.getInstance().cancelTask();
    }

    @Override
    public void onGetMessageCount(int messageCount) {
        JXUiHelper.getInstance().setMessageBoxUnreadCount(messageCount);
        setUpBadgeUnread(messageCount);
    }

    /**
     * 显示为读数
     * @param messageCount
     */
    private void setUpBadgeUnread(int messageCount) {
        if(msgBoxEnable){
            if(messageCount > 99){
                if(badgeTextView.getVisibility() != View.VISIBLE){
                    badgeTextView.setVisibility(View.VISIBLE);
                }
                badgeTextView.setText("...");
            }else if(messageCount > 0){
                if(badgeTextView.getVisibility() != View.VISIBLE){
                    badgeTextView.setVisibility(View.VISIBLE);
                }
                badgeTextView.setText(String.valueOf(messageCount));
            }else{
                if(badgeTextView.getVisibility() == View.VISIBLE){
                    badgeTextView.setVisibility(View.GONE);
                }
            }
        }
    }
    @Override
    public void onEvent(JXEventNotifier eventNotifier) {
        if(eventNotifier.getEvent() == JXEventNotifier.Event.MESSAGE_PUSH && msgBoxEnable){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int messageCount = JXUiHelper.getInstance().getMessageBoxUnreadCount();
                    setUpBadgeUnread(messageCount);
                }
            });
        }
    }

    public void reRequestCustomerService(String skillId) {
        loadingProgressBar.setVisibility(View.VISIBLE);
        JXRequestCusServiceTask cusServiceTask = new JXRequestCusServiceTask(suborgId,skillId, extendData,
                new JXRequestCusServiceTask.RequestCusServiceCallback() {
                    @Override
                    public void onRequestCallback(int code, int tag, boolean isNeedFinishAty, String
                            message) {
                        fetchWorkgroupFromServer();
                    }
                }, null);
        cusServiceTask.setTransferTag(JXUiHelper.TAG_CLOSE_SESSION, true);
        cusServiceTask.execute();
    }

    public void reRequestCustomerServiceByChatKey(String lastSkillId , final String skillId, final String chatTitlekey) {
        loadingProgressBar.setVisibility(View.VISIBLE);
        JXRequestCusServiceTask cusServiceTask = new JXRequestCusServiceTask(suborgId,lastSkillId, extendData,
                new JXRequestCusServiceTask.RequestCusServiceCallback() {
                    @Override
                    public void onRequestCallback(int code, int tag, boolean isNeedFinishAty, String
                            message) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        requestCustomerService(skillId, chatTitlekey);
                    }
                }, null);
        cusServiceTask.setTransferTag(JXUiHelper.TAG_CLOSE_SESSION, true);
        cusServiceTask.execute();
    }

    JXServiceTypeAdapter.OnChooseServiceTypeListener onChooseServiceTypeListener = new JXServiceTypeAdapter.OnChooseServiceTypeListener() {
        @Override
        public void onchoose(final JXServiceType serviceType) {
            backToServiceType = true;
            JXImManager.Config.getInstance().setServiceId(serviceType.getId());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (serviceType.getWorkgroupList().size() ==1){
                        //只有一个对应技能组 直接进入
                        requestCustomerService(serviceType.getWorkgroupList().get(0).getMcsId(), serviceType.getWorkgroupList().get(0).getDisplayName());
                    }else {
                        workGroupAdapter = new JXWorkGroupAdapter(JXInitActivity.this, serviceType.getWorkgroupList());
                        workGroupAdapter.setOnEnterGroupListener(JXInitActivity.this);
                        groupListView.setAdapter(workGroupAdapter);
                    }
                }
            });
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (backToServiceType){
                if (serviceTypeAdapter == null){
                    serviceTypeAdapter = new JXServiceTypeAdapter(JXInitActivity.this, currentCustomerServiceEntity.getServerTypes());
                    serviceTypeAdapter.setOnChooseServiceTypeListener(onChooseServiceTypeListener);
                }
                groupListView.setAdapter(serviceTypeAdapter);
                backToServiceType = false;
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
